package exercise16;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class MoveBall extends JFrame implements ActionListener{
	/*16-3的编程题*/
	
	private JButton jbtLeft = new JButton("Left");
	private JButton jbtRight = new JButton("Right");
	private JButton jbtUp = new JButton("Up");
	private JButton jbtDown = new JButton("Down");
	
	DisplayPanel panel = new DisplayPanel();
	
	public MoveBall(){
		add(panel, BorderLayout.CENTER);
		
		JPanel jbtPanel = new JPanel();
		jbtPanel.setLayout(new GridLayout(1, 4));
		jbtPanel.add(jbtLeft);
		jbtPanel.add(jbtRight);
		jbtPanel.add(jbtUp);
		jbtPanel.add(jbtDown);
		add(jbtPanel,BorderLayout.SOUTH);
		
		jbtLeft.addActionListener(this);
		jbtRight.addActionListener(this);
		jbtUp.addActionListener(this);
		jbtDown.addActionListener(this);
		
	}
	
	public void actionPerformed(ActionEvent e){
		if (e.getSource() == jbtLeft) {
			panel.moveLeft();
			System.out.println("moveLeft");
		}
		else if (e.getSource() == jbtRight) {
			panel.moveRight();
			System.out.println("moveRight");
		}
		else if (e.getSource() == jbtUp) {
			panel.moveUp();
			System.out.println("moveUp");
		}
		else if (e.getSource() == jbtDown) {
			panel.moveDown();
			System.out.println("moveDown");
		}
	}
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		JFrame frame = new MoveBall();
		frame.setTitle("MoveBall");
		frame.setSize(400, 200);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);

	}
	
	class DisplayPanel extends JPanel{
		private int xPoint = 50;
		private int yPoint = 50;
		
		public void moveUp(){
			yPoint -= 20;
			repaint();
		}
		
		public void moveDown(){
			yPoint += 20;
			repaint();
		}
		
		public void moveLeft(){
			xPoint -= 20;
			repaint();
		}
		
		public void moveRight(){
			xPoint += 20;
			repaint();
		}
		
		protected void paintComponent(Graphics g){
			super.paintComponent(g);
			
			g.drawOval(xPoint, yPoint, 20, 20);
			System.out.printf("x = %3d, y = %3d\n", xPoint, yPoint);
		}
	}

}
